package com.ecole.mines.emargement;

import java.util.ArrayList;
import java.util.Comparator;

import android.app.Fragment;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ecole.mines.model.Eleve;
import com.ecole.mines.model.Signature;
import com.ecole.mines.utils.ListEleveAdapter;

public class FragmentListeEleves extends Fragment implements TextWatcher,
		OnItemClickListener {

	private ListView listeEleve;
	private EditText champRechercheEleve;
	private TextView messageInfo;
	SignatureView signatureView;
	ArrayList<Eleve> eleves = new ArrayList<Eleve>();

	private Button annuler;
	private Button valider;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.activity_fragment_liste_eleves,
				container, false);

		listeEleve = (ListView) view.findViewById(R.id.listEleves);
		champRechercheEleve = (EditText) view.findViewById(R.id.rechercheEleve);
		messageInfo = (TextView) view.findViewById(R.id.messageInfo);

		this.listeEleve.setOnItemClickListener(this);
		champRechercheEleve.addTextChangedListener(this);

		setAnnuler((Button) getActivity().findViewById(R.id.buttonAnnuler));
		setValider((Button) getActivity().findViewById(R.id.buttonValider));

		return view;
	}

	/**
	 * Active les boutons et les rend visibles
	 * 
	 * @param valider
	 * @param annuler
	 */
	public static void activerBoutons(Button btnvalider, Button btnannuler) {
		btnvalider.setEnabled(true);
		btnvalider.setVisibility(View.VISIBLE);

		btnannuler.setEnabled(true);
		btnannuler.setVisibility(View.VISIBLE);

	}

	/**
	 * Désactive les boutons et les rends invisibles
	 * 
	 * @param btnvalider
	 * @param btnannuler
	 */
	public static void desactiverBoutons(Button btnvalider, Button btnannuler) {

		btnvalider.setEnabled(false);
		btnvalider.setVisibility(View.INVISIBLE);

		btnannuler.setEnabled(false);
		btnannuler.setVisibility(View.INVISIBLE);
	}

	/**
	 * Désactive les boutons et les rends invisibles
	 * 
	 * @param valider
	 * @param annuler
	 */

	protected void controleZoneSignature(Bitmap signatureBitmapSave,
			Eleve eleveSelectionne) {
		FragmentCadreSignature fragCadreSignature = (FragmentCadreSignature) getFragmentManager()
				.findFragmentById(R.id.fragmentCadreSignature);

		// Zone de signature activée sans validation
		if (signatureView.isSignatureActive()
				&& !signatureView.getZoneSignatureVide()) {
			((EmargementActivity) getActivity()).confirmChangementEleve(
					fragCadreSignature, eleveSelectionne, signatureBitmapSave);

		}

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		/*
		 * int textlength = champRechercheEleve.getText().length();
		 * this.arr_sort.clear(); for (int i = 0; i < listeEleves.size(); i++) {
		 * if (textlength <= listeEleves.get(i).length()) { if
		 * (champRechercheEleve.getText() .toString() .equalsIgnoreCase(
		 * (String) listeEleves.get(i).subSequence(0, textlength)))
		 * arr_sort.add(listeEleves.get(i)); } } ListEleveAdapter adapter = new
		 * ListEleveAdapter
		 * (getActivity(),R.layout.activity_emargement,this.arr_sort);
		 * listeEleve.setAdapter(adapter);
		 */

	}

	// -- Pour le tri du tableau
	Comparator<String> comperator = new Comparator<String>() {
		public int compare(String object1, String object2) {
			return object1.compareToIgnoreCase(object2);
		}
	};

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	public void majListeEleve(ArrayList<Eleve> eleves) {
		if (eleves != null && eleves.size() != 0) {
			// Création et initialisation de l'Adapter pour les personnes
			ListEleveAdapter adapter = new ListEleveAdapter(getActivity(),
					R.layout.activity_main, eleves);

			// Initialisation de la liste avec les données
			this.listeEleve.setAdapter(adapter);
			this.messageInfo.setVisibility(View.INVISIBLE);
			this.listeEleve.setVisibility(View.VISIBLE);
			this.champRechercheEleve.setVisibility(View.VISIBLE);

		} else {
			this.messageInfo.setVisibility(View.VISIBLE);
			this.listeEleve.setVisibility(View.INVISIBLE);
			this.champRechercheEleve.setVisibility(View.INVISIBLE);
			this.messageInfo.setText("Aucun élève trouvé");
		}
	}

	/*
	 * Getters et Setters
	 */

	public Button getAnnuler() {
		return annuler;
	}

	public void setAnnuler(Button annuler) {
		this.annuler = annuler;
	}

	public Button getValider() {
		return valider;
	}

	public void setValider(Button valider) {
		this.valider = valider;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		signatureView = (SignatureView) getActivity()
				.findViewById(R.id.drawing);
		signatureView
				.setFragListeEleves((FragmentListeEleves) getFragmentManager()
						.findFragmentById(R.id.fragmentListeEleves));
		// Contrôle de la zone de signature
		Bitmap signatureBitmapSave = Bitmap.createBitmap(signatureView
				.enregistrerSignature());
		controleZoneSignature(signatureBitmapSave,
				signatureView.eleveSelectionne);

		// TODO Auto-generated method stub
		Eleve eleveSelectionne = (Eleve) parent.getItemAtPosition(position);
		Toast.makeText(getActivity(),
				eleveSelectionne.getNom() + "(" + id + ")", Toast.LENGTH_SHORT)
				.show();

		// Afficher la signature existante, sinon effacer la zone de signature
		// On affecte l'éleve sélectionnée à la vue de la signature
		// Eleve eleveSelectionne = (Eleve)
		// eleves.get(Integer.valueOf(String.valueOf(id)));
		signatureView.eleveSelectionne = eleveSelectionne;
		setAnnuler((Button) getActivity().findViewById(R.id.buttonAnnuler));
		setValider((Button) getActivity().findViewById(R.id.buttonValider));

		if (eleveSelectionne.getSignatures().size() > 0) {
			signatureView.setEnabled(false);

			Signature signatureSaved = (Signature) eleveSelectionne
					.getSignatures().get(0);
			System.out.println("Signature " + eleveSelectionne.getNom() + " "
					+ signatureSaved.getImageSignature());
			if(signatureSaved.getImageSignature()!=null)
			{
				signatureView.chargerSignature(Bitmap.createBitmap(signatureSaved.getImageSignature()));
			}

			signatureView.setSignatureActive(false);

		} else {
			signatureView.setEnabled(true);
			signatureView.setupDrawing();
			// Effacer la zone de signature
			signatureView.effacerZoneSignature();
			signatureView.setSignatureActive(true);

		}

	}

}
